package com.daxia.bumall.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daxia.bumall.dao.SeedDAO;
import com.daxia.bumall.dto.SeedDTO;
import com.daxia.bumall.model.Seed;
import com.daxia.bumall.support.Page;
import com.daxia.bumall.util.BeanMapper;

@Service
public class SeedService {
	
	@Autowired
	private SeedDAO seedDAO;
	
	public List<SeedDTO> find(SeedDTO query, Page page) {
		List<Seed> models = seedDAO.find(query, page);
		List<SeedDTO> dtos = toDTOs(models);
		return dtos;
	}
	
	public List<SeedDTO> findAll() {
		return this.find(new SeedDTO(), null);
	}
	
	public List<SeedDTO> find(int count) {
		Page page = new Page();
		page.setPage(1);
		page.setPageSize(count);
		return this.find(new SeedDTO(), page);
	}
	
	public Long create(SeedDTO dto) {
		Seed model = new Seed();
		toModel(model, dto);
		return seedDAO.create(model);
	}
	
	public SeedDTO load(Long id) {
	    Seed model = seedDAO.load(id);
	    return toDTO(model);
    }

	public void updateAllFields(SeedDTO dto) {
		Seed model = seedDAO.load(dto.getId());
		toModel(model, dto);
		seedDAO.update(model);
    }

	public void deleteByIds(Long[] ids) {
		if (ids != null) {
			for (Long id : ids) {
				seedDAO.deleteById(id);
			}
		}
    }
	
	public void deleteById(Long id) {
		this.deleteByIds(new Long[] {id});
	}

	public SeedDTO findOne(SeedDTO query) {
		Seed model = seedDAO.findOne(query);
		return toDTO(model);
	}
	
	private List<SeedDTO> toDTOs(List<Seed> models) {
		if (CollectionUtils.isEmpty(models)) {
			return new ArrayList<SeedDTO>(0);
		}
		List<SeedDTO> dtos = new ArrayList<SeedDTO>(models.size());
		for (Seed model : models) {
	        SeedDTO dto = toDTO(model);
	        dtos.add(dto);
        }
	    return dtos;
    }
    
    private SeedDTO toDTO(Seed model) {
		if (model == null) {
			return null;
		}
		SeedDTO dto = BeanMapper.map(model, SeedDTO.class);
		
		return dto;
	}
	
	private void toModel(Seed model, SeedDTO dto) {
		BeanMapper.copy(dto, model);
    }
	
	@SuppressWarnings("unused")
	private List<Seed> toModels(List<SeedDTO> dtos) {
		if (CollectionUtils.isEmpty(dtos)) {
			return new ArrayList<Seed>(0);
		}
		List<Seed> models = new ArrayList<Seed>(dtos.size());
		for (SeedDTO dto : dtos) {
	        Seed model = new Seed();
	        toModel(model, dto);
	        models.add(model);
        }
		return models;
	}
}
